<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form 
        :model="loginForm" 
        :rules="loginRules"
        ref="loginFormRef"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit"
            class="login-btn"
          >
            立即登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /* 修改时间：2024-04-21 16:20:00 */
    handleLogin() {
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.$axios.post('/api/users/login', this.loginForm)
            .then(res => {
              if (res.data && (res.data.message === 'Login successful' || res.data.token)) {
                localStorage.setItem('token', res.data.token || 'logged-in')
                localStorage.setItem('userInfo', JSON.stringify(res.data.user || {}))
                this.$message.success('登录成功')
                this.$router.push('/admin')
              } else {
                this.$message.error(typeof res.data === 'string' ? res.data : '登录失败')
              }
            })
            .catch(err => {
              console.error('登录错误:', err)
              this.$message.error('登录失败：' + (err.response?.data?.message || err.message || '未知错误'))
            })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>